package com.haoniu.web.controller.common;

import com.haoniu.common.base.AjaxResult;
import com.haoniu.common.config.Global;
import com.haoniu.common.constant.Constants;
import com.haoniu.common.service.FileUploadService;
import com.haoniu.framework.util.FileUploadUtils;
import com.haoniu.framework.web.service.RedisService;
import com.haoniu.web.core.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController {

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    private RedisService redisService;

    /**
     * 文本编辑器上传图片
     *
     * @param uploadFile
     * @returnh
     * @throws Exception
     */
    @RequestMapping(value = "/textUploadImg", method = {RequestMethod.POST})
    @ResponseBody
    public AjaxResult textUploadImg(@RequestParam(value = "imgFile", required = false) MultipartFile uploadFile)
            throws Exception {
        String url = fileUploadService.uploadFile(uploadFile, "user");
        String fileBaseUrl = fileUploadService.getFileBaseUrl();
        return new AjaxResult().put("path", fileBaseUrl + url);
    }

    /**
     * 上传图片
     *
     * @param uploadFile
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadImg", method = {RequestMethod.POST})
    @ResponseBody
    public AjaxResult upload(@RequestParam(value = "file", required = false) MultipartFile uploadFile,
                             @RequestParam(value = "imgType", required = false) String imgType)
            throws Exception {
        String path = redisService.getConfig("file.upload.path");
        String url = FileUploadUtils.upload(path+"/"+imgType+"/",uploadFile);
        return AjaxResult.success(Constants.SUCCESS_MSG, "/fileUpload/"+imgType+"/"+url);
    }

}
